//
//  SISSRateBarView.m
//  test
//
//  Created by 优房网 on 2017/7/17.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSRateBarView.h"
#import "SISSRateStarView.h"

@interface SISSRateBarView ()

///
@property (weak, nonatomic) UIView *baseView;

/// stars
@property (strong, nonatomic) NSMutableArray *stars;

@end
@implementation SISSRateBarView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.rate = 0;
        self.maxRateValue = 5;
        self.starBackgroundColor = [UIColor groupTableViewBackgroundColor];
        UIView *baseView = [[UIView alloc] init];
        [self addSubview:baseView];
        self.baseView = baseView;
       
    }
    return self;
}

- (void)setRate:(NSInteger)rate {
    _rate = rate;
    [self setNeedsLayout];
}

- (void)setStarTintColor:(UIColor *)starTintColor {
    _starTintColor = starTintColor;
}

- (void)setMaxRateValue:(NSInteger)maxRateValue {
    _maxRateValue = maxRateValue;
    self.stars = [NSMutableArray arrayWithCapacity:maxRateValue];
    for (NSInteger i = 0; i < maxRateValue; i++) {
        SISSRateStarView *star = [[SISSRateStarView alloc] init];
        [self.stars addObject:star];
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(starViewDidTap:)];
        [star addGestureRecognizer:tapGesture];
    }
}

- (void)starViewDidTap:(UITapGestureRecognizer *)tapRecognizer {
    
    SISSRateStarView *starView = (SISSRateStarView *)tapRecognizer.view;
    NSInteger index = [self.stars indexOfObject:starView];
    if ([self.delegate respondsToSelector:@selector(rateBarViewDidSelectedRateBarView:atIndex:)]) {
        [self.delegate rateBarViewDidSelectedRateBarView:self atIndex:index + 1];
    }
    
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.baseView.center = self.center;
    self.baseView.frame = CGRectMake(5, 3, self.frame.size.width - 10, self.frame.size.height - 6);
    CGFloat margin = 3;
    CGFloat width = self.baseView.frame.size.height;
    CGFloat height = width;
    for (NSInteger i = 0; i < self.maxRateValue; i++) {
        SISSRateStarView *star = self.stars[i];
        star.frame = CGRectMake((width + margin) * i + margin, 0, width, height);
        if (i <= self.rate - 1) {
            star.starColor = self.starTintColor;
        } else {
            star.starColor = self.starBackgroundColor;
        }
        [self.baseView addSubview:star];
    }
}

@end
